from rest_framework import generics, status, permissions
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from django.db import transaction, models
from django.utils import timezone
from .models import Game, GameRound, PlayerAction
from .serializers import GameSerializer, GameRoundSerializer, PlayCardSerializer
from .game_logic import GameLogic


class GameListView(generics.ListAPIView):
    """获取用户游戏列表"""
    serializer_class = GameSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def get_queryset(self):
        return Game.objects.filter(
            models.Q(player1=self.request.user) | models.Q(player2=self.request.user)
        )


class GameDetailView(generics.RetrieveAPIView):
    """获取游戏详情"""
    serializer_class = GameSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def get_queryset(self):
        return Game.objects.filter(
            models.Q(player1=self.request.user) | models.Q(player2=self.request.user)
        )


@api_view(['POST'])
@permission_classes([permissions.IsAuthenticated])
def play_card(request, game_id):
    """出牌"""
    try:
        game = Game.objects.get(id=game_id)
    except Game.DoesNotExist:
        return Response({'error': '游戏不存在'}, status=status.HTTP_404_NOT_FOUND)
    
    # 检查用户是否参与此游戏（AI游戏的player2为None）
    if request.user != game.player1 and (game.player2 and request.user != game.player2):
        return Response({'error': '您没有参与此游戏'}, status=status.HTTP_403_FORBIDDEN)
    
    serializer = PlayCardSerializer(data=request.data)
    if serializer.is_valid():
        card_id = serializer.validated_data['card_id']
        
        # 获取卡牌对象
        try:
            from apps.cards.models import Card
            card = Card.objects.get(id=card_id)
        except Card.DoesNotExist:
            return Response({'error': '卡牌不存在'}, status=status.HTTP_404_NOT_FOUND)
        
        # 检查是否是AI游戏
        if game.player2 is None and game.player2_deck is not None:
            # AI游戏，使用AI出牌逻辑
            success, message = GameLogic.play_card_with_ai(game, request.user, card)
        else:
            # 玩家对战，使用普通出牌逻辑
            success, message = GameLogic.play_card(game, request.user, card)
            
            # 玩家对战时，出牌后检查回合是否结束
            if success:
                current_round = game.rounds.filter(is_finished=False).first()
                if current_round and current_round.player1_card and current_round.player2_card:
                    # 双方都已出牌，结束回合
                    GameLogic.finish_round(current_round)
        
        if success:
            return Response({'message': message})
        else:
            return Response({'error': message}, status=status.HTTP_400_BAD_REQUEST)
    
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET'])
@permission_classes([permissions.IsAuthenticated])
def game_status(request, game_id):
    """获取游戏状态"""
    try:
        game = Game.objects.get(id=game_id)
    except Game.DoesNotExist:
        return Response({'error': '游戏不存在'}, status=status.HTTP_404_NOT_FOUND)
    
    # 检查用户是否参与此游戏（AI游戏的player2为None）
    if request.user != game.player1 and (game.player2 and request.user != game.player2):
        return Response({'error': '您没有参与此游戏'}, status=status.HTTP_403_FORBIDDEN)
    
    status_data = GameLogic.get_game_status(game)
    return Response(status_data)


@api_view(['POST'])
@permission_classes([permissions.IsAuthenticated])
def join_game(request, game_id):
    """加入游戏"""
    try:
        game = Game.objects.get(id=game_id, status='waiting')
    except Game.DoesNotExist:
        return Response({'error': '游戏不存在或已开始'}, status=status.HTTP_404_NOT_FOUND)
    
    if game.player1 == request.user:
        return Response({'error': '您已经在游戏中了'}, status=status.HTTP_400_BAD_REQUEST)
    
    if game.player2 is not None:
        return Response({'error': '游戏已满员'}, status=status.HTTP_400_BAD_REQUEST)
    
    # 获取用户选择的卡组
    deck_id = request.data.get('deck_id')
    if not deck_id:
        return Response({'error': '请选择卡组'}, status=status.HTTP_400_BAD_REQUEST)
    
    try:
        from apps.decks.models import Deck
        deck = Deck.objects.get(id=deck_id, user=request.user, is_active=True)
    except Deck.DoesNotExist:
        return Response({'error': '卡组不存在'}, status=status.HTTP_404_NOT_FOUND)
    
    # 检查卡组是否完整
    if deck.total_cards != 5:
        return Response({'error': '卡组必须包含5张卡牌'}, status=status.HTTP_400_BAD_REQUEST)
    
    with transaction.atomic():
        game.player2 = request.user
        game.player2_deck = deck
        game.save()
        
        # 开始游戏
        GameLogic.start_game(game)
    
    return Response({'message': '成功加入游戏'})


@api_view(['POST'])
@permission_classes([permissions.IsAuthenticated])
def ai_play_card(request, game_id):
    """AI出牌"""
    try:
        game = Game.objects.get(id=game_id)
    except Game.DoesNotExist:
        return Response({'error': '游戏不存在'}, status=status.HTTP_404_NOT_FOUND)
    
    # 检查用户是否参与此游戏（AI游戏的player2为None）
    if request.user != game.player1 and (game.player2 and request.user != game.player2):
        return Response({'error': '您没有参与此游戏'}, status=status.HTTP_403_FORBIDDEN)
    
    # 检查是否是AI游戏
    if game.player2 is not None or game.player2_deck is None:
        return Response({'error': '这不是AI游戏'}, status=status.HTTP_400_BAD_REQUEST)
    
    # 获取当前回合
    current_round = game.rounds.filter(is_finished=False).first()
    if not current_round:
        return Response({'error': '没有进行中的回合'}, status=status.HTTP_400_BAD_REQUEST)
    
    # AI出牌
    success, message = GameLogic.ai_play_card(game, current_round)
    if not success:
        return Response({'error': message}, status=status.HTTP_400_BAD_REQUEST)
    
    # 重新获取回合信息（因为AI出牌后回合可能已经结束）
    current_round.refresh_from_db()
    
    # 检查回合是否结束
    if current_round.player1_card and current_round.player2_card:
        GameLogic.finish_round(current_round)
    
    return Response({'message': message})


@api_view(['POST'])
@permission_classes([permissions.IsAuthenticated])
def create_next_round(request, game_id):
    """创建下一回合（支持AI游戏和玩家对战）"""
    try:
        game = Game.objects.get(id=game_id)
    except Game.DoesNotExist:
        return Response({'error': '游戏不存在'}, status=status.HTTP_404_NOT_FOUND)
    
    # 检查用户是否参与此游戏
    if request.user != game.player1 and (game.player2 and request.user != game.player2):
        return Response({'error': '您没有参与此游戏'}, status=status.HTTP_403_FORBIDDEN)
    
    # 检查游戏是否已结束
    if game.status == 'finished':
        return Response({'error': '游戏已结束'}, status=status.HTTP_400_BAD_REQUEST)
    
    # 检查是否还有未完成的回合
    current_round = game.rounds.filter(is_finished=False).first()
    if current_round:
        return Response({'error': '当前回合尚未结束'}, status=status.HTTP_400_BAD_REQUEST)
    
    # 创建下一回合
    finished_rounds = game.rounds.filter(is_finished=True).count()
    next_round_number = finished_rounds + 1
    
    # 检查是否超过最大回合数
    if next_round_number > game.max_rounds:
        return Response({'error': '已达到最大回合数'}, status=status.HTTP_400_BAD_REQUEST)
    
    with transaction.atomic():
        # 创建下一回合
        GameRound.objects.create(
            game=game,
            round_number=next_round_number
        )
        
        # 更新游戏当前回合数
        game.current_turn = next_round_number
        game.save()
    
    return Response({
        'message': f'第{next_round_number}回合开始',
        'round_number': next_round_number
    })


@api_view(['POST'])
@permission_classes([permissions.IsAuthenticated])
def start_ai_game(request):
    """开始人机对战"""
    deck_id = request.data.get('deck_id')
    if not deck_id:
        return Response({'error': '请选择卡组'}, status=status.HTTP_400_BAD_REQUEST)
    
    try:
        from apps.decks.models import Deck
        deck = Deck.objects.get(id=deck_id, user=request.user, is_active=True)
    except Deck.DoesNotExist:
        return Response({'error': '卡组不存在'}, status=status.HTTP_404_NOT_FOUND)
    
    # 检查卡组是否完整
    if deck.total_cards != 5:
        return Response({'error': '卡组必须包含5张卡牌'}, status=status.HTTP_400_BAD_REQUEST)
    
    with transaction.atomic():
        # 创建AI游戏
        game = Game.objects.create(
            player1=request.user,
            player1_deck=deck,
            status='playing'
        )
        
        # 创建AI卡组（固定卡组）
        ai_deck = GameLogic.create_ai_deck()
        game.player2_deck = ai_deck
        game.save()
        
        # 开始游戏
        GameLogic.start_game(game)
    
    return Response({
        'message': '人机对战开始',
        'game_id': game.id
    })

@api_view(['GET'])
@permission_classes([permissions.IsAuthenticated])
def game_user_info(request, game_id):
    """获取游戏中的用户信息"""
    try:
        game = Game.objects.get(id=game_id)
    except Game.DoesNotExist:
        return Response({'error': '游戏不存在'}, status=status.HTTP_404_NOT_FOUND)
    
    # 检查用户是否参与此游戏
    if request.user != game.player1 and (game.player2 and request.user != game.player2):
        return Response({'error': '您没有参与此游戏'}, status=status.HTTP_403_FORBIDDEN)
    
    # 确定用户是player1还是player2
    is_player1 = request.user == game.player1
    
    return Response({
        'user_id': request.user.id,
        'is_player1': is_player1,
        'player1_id': game.player1.id,
        'player2_id': game.player2.id if game.player2 else None
    })


@api_view(['POST'])
@permission_classes([permissions.IsAuthenticated])
def finish_game(request, game_id):
    """结束游戏"""
    try:
        game = Game.objects.get(id=game_id)
    except Game.DoesNotExist:
        return Response({'error': '游戏不存在'}, status=status.HTTP_404_NOT_FOUND)
    
    # 检查用户是否参与此游戏
    if request.user != game.player1 and (game.player2 and request.user != game.player2):
        return Response({'error': '您没有参与此游戏'}, status=status.HTTP_403_FORBIDDEN)
    
    # 检查游戏是否已经有winner但未设置为finished
    if game.winner and game.status != 'finished':
        game.status = 'finished'
        game.finished_at = timezone.now()
        game.save()
        
        return Response({
            'message': '游戏已结束',
            'winner': {
                'id': game.winner.id,
                'nickname': game.winner.nickname
            } if game.winner else None
        })
    else:
        return Response({'error': '游戏状态异常'}, status=status.HTTP_400_BAD_REQUEST)